package handlers

import (
	"errors"
	"strconv"

	"github.com/yjp211/web"

	"mutu/misc/conf"
	"mutu/misc/typedef"
	"mutu/service"
)

type TagView struct{}

var (
	TagHandler = TagView{}
)

func (p TagView) GetAllClasses(ctx *web.Context) string {
	var data typedef.Dict
	arr, err := service.TagService.GetAllClasses()
	if err == nil {
		data = typedef.Dict{
			"count": len(arr),
			"arr":   arr,
		}
	}
	return JsonpReturn(ctx, data, err)
}

func (p TagView) GetTagsByClass(ctx *web.Context) string {
	classid, err := strconv.Atoi(ctx.Params["classid"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	var data typedef.Dict
	arr, err := service.TagService.GetTagsByClass(classid)
	if err == nil {
		data = typedef.Dict{
			"count": len(arr),
			"arr":   arr,
		}
	}
	return JsonpReturn(ctx, data, err)
}

func (p TagView) GetTagsByClassName(ctx *web.Context) string {
	name, ok := ctx.Params["name"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	var data typedef.Dict
	arr, err := service.TagService.GetTagsByClassName(name)
	if err == nil {
		data = typedef.Dict{
			"count": len(arr),
			"arr":   arr,
		}
	}
	return JsonpReturn(ctx, data, err)
}

func (p TagView) GetAllTags(ctx *web.Context) string {
	var data typedef.Dict
	arr, err := service.TagService.GetAllTags()
	if err == nil {
		data = typedef.Dict{
			"count": len(arr),
			"arr":   arr,
		}
	}
	return JsonpReturn(ctx, data, err)
}

func (p TagView) GetAllTagsWithCount(ctx *web.Context) string {
	flag, err := strconv.Atoi(ctx.Params["flag"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	if flag == 1 {
		flag = conf.F_Matter_PIC
	} else if flag == 2 {
		flag = conf.F_Matter_PSD
	} else {
		flag = 0
	}

	var data typedef.Dict
	arr, err := service.TagService.GetAllTagsWithRelCount(flag)
	if err == nil {
		data = typedef.Dict{
			"count": len(arr),
			"arr":   arr,
		}
	}
	return JsonpReturn(ctx, data, err)
}
